package plugin;

import java.io.*;
import java.net.*;

import org.json.JSONObject;

public class EANDataPlugin implements IProductIDPlugin
{
	private static final int ONE_SECOND = 1000;
	private static final String APIKEY = "19CE35FD51679F37";
	private static final int BARCODE_SIZE = 12;
	public EANDataPlugin()
	{
		
	}
	
	@Override
	public String identifyProduct(String barcode) throws Exception {
		
		if (barcode.length() < BARCODE_SIZE)
		{
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < BARCODE_SIZE - barcode.length(); i++)
				sb.append("0");
			sb.append(barcode);
			barcode = sb.toString();
		}
		if (barcode.length() > BARCODE_SIZE)
			throw new Exception ("Barcode too big");
		String urlString = "http://eandata.com/feed.php?keycode=" + APIKEY +
				"&mode=json&find=" + barcode;
		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();
		conn.setConnectTimeout(ONE_SECOND);
		conn.setReadTimeout(ONE_SECOND * 100);

		InputStream responseBody = conn.getInputStream();
		BufferedReader bReader = new BufferedReader(new InputStreamReader(responseBody));
		StringBuilder sb = new StringBuilder();
		String inline = "";
		while ((inline = bReader.readLine()) != null) {
	          sb.append(inline);
	        }
		return getDescriptionFromJson(sb.toString());
	}
	
	private String getDescriptionFromJson(String string){
		JSONObject jObj = new JSONObject(string);
		JSONObject projObj = jObj.getJSONObject("product");
		String descr = projObj.getString("product");
		return descr;
	}
}
